#include "graph.hpp"

using namespace std;

Graph::Graph()
{
	if (SDL_Init(SDL_INIT_VIDEO)<0)
	{ 
		printf("SDL: INIT_ERROR(%s)\n", SDL_GetError()); 
		exit(1); 
 	}
 	else 
	{
		puts("SDL: STARTED");
		SDL_WM_SetCaption(Defined::WindowCaption.c_str(),NULL);
		SDL_WM_SetIcon(SDL_LoadBMP(Defined::PathToIcon.c_str()), NULL);
	}
}

void Graph::LockSurface(SDL_Surface *screen)
{
	if (SDL_MUSTLOCK(screen))
	   if (SDL_LockSurface(screen)<0); ///What da F@CK???
}

void Graph::UnlockSurface(SDL_Surface *screen)
{
 	if (SDL_MUSTLOCK(screen)) SDL_UnlockSurface(screen); 
} 

void Graph::SetSurface(SDL_Surface **screen, int x,int y)
{
	SDL_Surface *tempscreen;
	widht=x;
	height=y;
	tempscreen=SDL_SetVideoMode(widht,height,32,SDL_HWSURFACE|SDL_DOUBLEBUF); 
 	if ( tempscreen == NULL )
 	{ 
		cout<<"SDL: ERROR(unable to set "<< widht << "x" << height << ". " << SDL_GetError() <<")"<< endl; 
  		exit(1); 
 	} 
 	*screen=tempscreen;
}

bool Graph::SaveSurface(SDL_Surface *screen, const char* filename)
{
	if ((SDL_SaveBMP(screen, filename))==0) return true;
	return false;
}

int Graph::DoubleToRGB(double f)
{
	double f2 = max(0.0,min(1.0,double(f)));
	int b=int(floor(f2==1.0 ? 255:f2*256.0));
	return b;
}

void Graph::DrawPixel(SDL_Surface *screen, Point myPoint)
{ 
	Color pointColor=myPoint.GetColor();
	
	int Red=DoubleToRGB(pointColor.GetRed());
	int Green=DoubleToRGB(pointColor.GetGreen());
	int Blue=DoubleToRGB(pointColor.GetBlue());
		
	int x=myPoint.GetX()%widht;
	int y=myPoint.GetY()%height;
	
	Uint32 color = SDL_MapRGB(screen->format, Red, Green, Blue); 
	switch (screen->format->BytesPerPixel)
	{ 
		case 1:  // Assuming 8-bpp 
		{ 
			Uint8 *bufp; 
			bufp = (Uint8 *)screen->pixels + y*screen->pitch + x; *bufp = color; 
		} break;
		case 2: // Probably 15-bpp or 16-bpp 
		{ 
			Uint16 *bufp; 
			bufp = (Uint16 *)screen->pixels + y*screen->pitch/2 + x; *bufp = color; 
		} break; 
		case 3: // Slow 24-bpp mode, usually not used 
		{ 
			Uint8 *bufp; 
			bufp = (Uint8 *)screen->pixels + y*screen->pitch + x * 3; 
			if(SDL_BYTEORDER == SDL_LIL_ENDIAN)
			{ 
				bufp[0] = color; 
				bufp[1] = color >> 8; 
				bufp[2] = color >> 16; 
			}
			else
			{ 
				bufp[2] = color; 
				bufp[1] = color >> 8; 
				bufp[0] = color >> 16; 
		     } 
		} break; 
		case 4: // Probably 32-bpp 
		{ 
			Uint32 *bufp; 
			bufp = (Uint32 *)screen->pixels + y*screen->pitch/4 + x; 
			*bufp = color; 
		} break; 
	} 
}
